package me.yricky.mayu.ui.fasta_box

import com.google.common.collect.HashBiMap
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import me.yricky.mayu.ui.fasta_list.FastaListModel
import me.yricky.mayu.utils.fasta.Fasta
import java.io.File

/**
 * @author Yricky
 * @date 2022/4/18
 */
class FastaBoxesModel {
    private val seqMap = HashBiMap.create<File, FastaListModel>()
    private val _keys:MutableStateFlow<List<File>> = MutableStateFlow(seqMap.keys.toList())

    fun add(f:File){
        if(seqMap[f] == null){
            seqMap[f] = FastaListModel(f.let{Fasta.readFile(it)})
            _keys.value = seqMap.keys.toList()
        }
        currentFocusedFasta.value = seqMap[f] ?: tempBox
    }

    fun remove(f:File){
        if(currentFocusedFasta.value == seqMap.remove(f)){
            _keys.value = seqMap.keys.toList()
            currentFocusedFasta.value = seqMap[_keys.value.lastOrNull()] ?: tempBox
        }else{
            _keys.value = seqMap.keys.toList()
        }
    }

    val tempBox = FastaListModel()
    val currentFocusedFasta = MutableStateFlow(tempBox)
    val keys = _keys.asStateFlow()
    fun getFasta(f:File) = seqMap[f]
    fun getFile(vm: FastaListModel) = seqMap.inverse()[vm]
}